package com.min.netty.codec;

import com.min.netty.model.LogEvent;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;

/**
 * CREATE BY 2018/9/10
 *
 * @author sirmin
 */
public class LogEventDecoder extends MessageToMessageDecoder<DatagramPacket> {

    @Override
    protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) {
        final SocketAddress socketAddress = msg.sender();
        final ByteBuf content = msg.content();
        final int index = content.indexOf(0, content.writerIndex(), LogEvent.SEPARATOR);
        final LogEvent logEvent = new LogEvent((InetSocketAddress) socketAddress, content.slice(0, index).toString(CharsetUtil.UTF_8),
                content.slice(index+1, content.writerIndex()).toString(CharsetUtil.UTF_8), System.currentTimeMillis());
        out.add(logEvent);
    }
}
